package com.ruix.app.widget;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Build;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.model.viewmodel.InputSubItem;
import com.ruix.app.ui.adapter.LessonInputViewAdapter;
import com.ruix.app.util.LogUitl;

import java.util.ArrayList;

/**
 * Created by hadexs on 2017/5/14.
 */

public class LessonInputView extends LinearLayout implements View.OnClickListener, LessonInputViewAdapter.OnItemClickLisenter {

    private ImageView changeInputType, messageButtonOther;
    private TextView sendVoiceBtn, sendMessageBtn,inputTipView;
    private EditText messageInputEdit;
    private View sendMessageContain, sendMessageBottomContain;
    private boolean sendVoice, showOhterInput;
    private RecyclerView recyclerView;
    private InputMethodManager inputManager;
    private ArrayList<InputSubItem> subItems;
    private LessonInputViewAdapter adapter;
    private OnOtherInputClickListener clickListener;
    protected Activity activity;
    private boolean noSendVoiceFunction; //没有发送语音的功能
    private View mContentView;
    private SharedPreferences sp;
    private static final String SHARE_PREFERENCE_TAG = "soft_input_height";
    private static final String SHARE_PREFERENCE_NAME = "com.emotioninputdetector";
    private LessonInputVoiceView voiceRecorderView;
//    private boolean hasRecordVoicePermission;//是否有录音权限  每次都检查 避免关闭权限后测试
    private int defaltHeight;


    public LessonInputView(Context context) {
        super(context);
        initView(context);
    }

    public LessonInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public LessonInputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }


    //
    private void initView(Context context) {
        this.activity = (Activity) context;
        LayoutInflater.from(context).inflate(R.layout.layout_lesson_bottom, this, true);
        sendMessageContain = findViewById(R.id.rl_send_message_contain);
        changeInputType = (ImageView) findViewById(R.id.iv_message_change_type);//左边切换框

        sendVoiceBtn = (TextView) findViewById(R.id.tv_send_voice);
        messageInputEdit = (EditText) findViewById(R.id.et_message_input);
        messageButtonOther = (ImageView) findViewById(R.id.iv_message_other_input);
        sendMessageBtn = (TextView) findViewById(R.id.btn_send_message);
        sendMessageBottomContain = findViewById(R.id.rl_bottom_View);

        voiceRecorderView = (LessonInputVoiceView)findViewById(R.id.rl_voice_input_view);
        inputTipView = (TextView) findViewById(R.id.input_tip_view);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4, GridLayoutManager.VERTICAL, false));
        adapter = new LessonInputViewAdapter(getContext(), this);
        recyclerView.setAdapter(adapter);
        defaultSendVoiceMessageView();
        setListener();
        inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//        context.
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        initLeftInputType();
        sp = activity.getSharedPreferences(SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
        defaltHeight = (int)context.getResources().getDimension(R.dimen.h_w_210);
    }

    private void initLeftInputType() {
        if (noSendVoiceFunction) {
            changeInputType.setVisibility(GONE);
        } else {
            changeInputType.setImageResource(R.drawable.lesson_msg_voice);
        }
    }


    //未录音的情况下
    public void init(){

    }

    //默认发送语音
    private void defaultSendVoiceMessageView() {
        sendVoice = false;
//        sendVoiceBtn.setVisibility(GONE);
        messageInputEdit.setVisibility(VISIBLE);
        sendMessageBottomContain.setVisibility(GONE);
        messageButtonOther.setVisibility(VISIBLE);
        sendMessageBtn.setVisibility(GONE);
    }

    private void setListener() {
        messageButtonOther.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sendMessageBottomContain.isShown()){
                    if (voiceRecorderView.isShown()){
                        voiceRecorderView.setVisibility(GONE);
                        recyclerView.setVisibility(VISIBLE);
                    } else if (recyclerView.isShown()){
                        lockContentHeight();
                        hideEmotionLayout(true);
                        unlockContentHeightDelayed();
                    }
                } else if (isSoftInputShown()) {
                    lockContentHeight();
                    showOtherInputView();
                    unlockContentHeightDelayed();
                } else {
                    showOtherInputView();
                }
            }
        });
        changeInputType.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSoftInputShown()){ //
                    showSendVoiceView(true);
                } else if (sendVoice) {
                    showSendMessageView();
                } else {
                    showSendVoiceView(false);
                }
            }
        });
        messageInputEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    sendMessageBtn.setVisibility(VISIBLE);
                    messageButtonOther.setVisibility(GONE);
                } else {
                    messageButtonOther.setVisibility(VISIBLE);
                    sendMessageBtn.setVisibility(GONE);
                }

            }
        });

        sendMessageBtn.setOnClickListener(this);
        sendVoiceBtn.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (clickListener != null) {
                    return clickListener.onPressToSpeakBtnTouch(v, event);
                }
                return false;
            }
        });

        messageInputEdit.requestFocus();
        messageInputEdit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP && sendMessageBottomContain.isShown()) {
                    if (sendVoice) {
                        sendVoice = false;
                        changeInputType.setImageResource(R.drawable.lesson_msg_voice);
                    }
                    lockContentHeight();
                    hideEmotionLayout(true);
                    unlockContentHeightDelayed();
                }
                return false;
            }
        });

//        recyclerView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (sendMessageBottomContain.isShown()) {
//                    sendMessageBottomContain.setVisibility(GONE);
//                }
//            }
//        });
        //
        voiceRecorderView.setVoiceInputListener(new LessonInputVoiceView.VoiceInputListener() {

            @Override
            public void showVoiceInputTip(String tip, int bgColor) {
                inputTipView.setVisibility(VISIBLE);
                inputTipView.setText(tip);
                inputTipView.setBackgroundColor(bgColor);
            }

            @Override
            public void hideVoiceInputTip() {
                inputTipView.setVisibility(GONE);
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send_message:
                String message = messageInputEdit.getText().toString().trim();
                if (clickListener != null) {
                    clickListener.sendInputeMessage(message);
                    messageInputEdit.setText("");
                }
                break;
        }
    }

    public boolean interceptBackPress() {
        if (sendMessageBottomContain.isShown()) {
            sendVoice = false;
            changeInputType.setImageResource(R.drawable.lesson_msg_voice);
            inputTipView.setVisibility(GONE); //TODO
            voiceRecorderView.updateView();
            hideEmotionLayout(false);
            return true;
        } else if (isSoftInputShown()) {
            hideSoftInput();
            return true;
        }
        return false;
    }

    public boolean isRecording(){
        return voiceRecorderView.isRecording();
    }

    public void closeRecorder(){
        voiceRecorderView.stopRecorder();
        sendVoice = false;
        changeInputType.setImageResource(R.drawable.lesson_msg_voice);
        hideEmotionLayout(false);
    }

    //隐藏键盘 展示发送语音
    private void showSendVoiceView(boolean hasLock) {
        if (clickListener != null) {//
            if (!clickListener.onCanRecordVoice()) {
                return;
            }
        }
        sendVoice = true;
        changeInputType.setImageResource(R.drawable.keyboard_btn_normal);
        if (hasLock) {
            lockContentHeight();
        }
        showEmotionLayout();
        if (hasLock) {
            unlockContentHeightDelayed();
        }
        recyclerView.setVisibility(GONE);
        voiceRecorderView.setVisibility(VISIBLE);
//        sendMessageBottomContain.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//
//                sendMessageBottomContain.requestLayout();
//            }
//        }, 200L);
    }



    //展示发送消息  展示键盘
    private void showSendMessageView(){
        sendVoice = false;
        changeInputType.setImageResource(R.drawable.lesson_msg_voice);
        if (sendMessageBottomContain.isShown()) {
            lockContentHeight();
            hideEmotionLayout(true);
            unlockContentHeightDelayed();
        } else {
            showSoftInput();
        }
    }


    private void showOtherInputView(){
        showEmotionLayout();
        voiceRecorderView.setVisibility(GONE);
        recyclerView.setVisibility(VISIBLE);
    }



    private void showVoiceInputView() {
        if (!sendMessageBottomContain.isShown()) {
            showEmotionLayout();
        }
        showEmotionLayout();
        voiceRecorderView.setVisibility(VISIBLE);
        recyclerView.setVisibility(GONE);
    }


    private void hideEmotionLayout(boolean showSoftInput) {
        if (sendMessageBottomContain.isShown()) {
            sendMessageBottomContain.setVisibility(View.GONE);
            if (showSoftInput) {
                showSoftInput();
            }
        }
    }


    private void lockContentHeight() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mContentView.getLayoutParams();
        params.height = mContentView.getHeight();
//        params.height = defaltHeight;
        params.weight = 0.0F;
    }

    private void unlockContentHeightDelayed() {
        mContentView.postDelayed(new Runnable() {
            @Override
            public void run() {
                ((LinearLayout.LayoutParams) mContentView.getLayoutParams()).weight = 1.0F;
            }
        }, 100L);
    }

    private void showEmotionLayout() {
        int softInputHeight = getSupportSoftInputHeight();
        if (softInputHeight == 0) {
            softInputHeight = sp.getInt(SHARE_PREFERENCE_TAG, defaltHeight);
        }
        if (isSoftInputShown()) {
            hideSoftInput();
        }
        ViewGroup.LayoutParams layoutParams = sendMessageBottomContain.getLayoutParams();
        layoutParams.height = softInputHeight;
        sendMessageBottomContain.setLayoutParams(layoutParams);
        sendMessageBottomContain.setVisibility(View.VISIBLE);

    }

    private void showSoftInput() {
        messageInputEdit.requestFocus();
        messageInputEdit.post(new Runnable() {
            @Override
            public void run() {
                inputManager.showSoftInput(messageInputEdit, 0);
            }
        });
    }




    private void hideSoftInput() {
//        messageInputEdit.post(new Runnable() {
//            @Override
//            public void run() {
//                inputManager.hideSoftInputFromWindow(messageInputEdit.getWindowToken(), 0);
//            }
//        });
        inputManager.hideSoftInputFromWindow(messageInputEdit.getWindowToken(), 0);

    }





    public void setSubItems(ArrayList<InputSubItem> subItems) {
        this.subItems = subItems;
        adapter.addAll(subItems);
        adapter.notifyDataSetHasChanged();
    }


    public void updateMuteState(boolean mute) {
        adapter.setMuted(mute);
        adapter.notifyDataSetChanged();
    }

    public void updateSubItemView(ArrayList<InputSubItem> subItems) {
        adapter.replaceAll(subItems);
        adapter.notifyDataSetHasChanged();
    }

    public void setClickListener(OnOtherInputClickListener clickListener) {
        this.clickListener = clickListener;
    }

    @Override
    public void onItemClicked(InputSubItem inputSubItem) {
        if (clickListener != null) {
            clickListener.onItemClicked(inputSubItem);
        }
    }


    public void setmContentView(View contentView) {
        this.mContentView = contentView;
//        mContentView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        mContentView.setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (event.getAction() == MotionEvent.ACTION_UP) {
//                    hideEmotionLayout(false);
//                    if (isSoftInputShown()){
//                        hideSoftInput();
//                    }
//                }
//                return false;
//            }
//        });
    }

    public interface OnOtherInputClickListener {
        void sendInputeMessage(String content);

        void onItemClicked(InputSubItem inputSubItem);

        boolean onPressToSpeakBtnTouch(View v, MotionEvent event);

        boolean onCanRecordVoice();

    }


    public void setNoSendVoiceFunction(boolean noSendVoiceFunction) {
        this.noSendVoiceFunction = noSendVoiceFunction;
        if (noSendVoiceFunction) {
            changeInputType.setVisibility(GONE);
        } else {
            changeInputType.setVisibility(VISIBLE);
        }
    }

    public void setSubInputHeight(int softHight) {
        if (softHight > 200) {
            ViewGroup.LayoutParams layoutParams = sendMessageBottomContain.getLayoutParams();
            layoutParams.height = softHight;
            layoutParams.width = LayoutParams.MATCH_PARENT;//
            sendMessageBottomContain.setLayoutParams(layoutParams);
        }
    }



    private boolean isSoftInputShown() {
        int height = getSupportSoftInputHeight();
//        return inputManager.isActive();
        return height != 0;
    }

    private int getSupportSoftInputHeight() {
        Rect r = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();
        int softInputHeight = screenHeight - r.bottom;
        if (Build.VERSION.SDK_INT >= 20) {
            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
            softInputHeight = softInputHeight - getSoftButtonsBarHeight();
        }
        if (softInputHeight < 0) {
            //
            Log.w("EmotionInputDetector", "Warning: value of softInputHeight is below zero!");
        }
        if (softInputHeight > 0) {
            sp.edit().putInt(SHARE_PREFERENCE_TAG, softInputHeight).apply();
        }
        return softInputHeight;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }


    public LessonInputVoiceView getVoiceRecorderView() {
        return voiceRecorderView;
    }

    public void setVoiceRecorderCallback(LessonInputVoiceView.VoiceRecorderCallback voiceRecorderCallback) {

        voiceRecorderView.setVoiceRecorderCallback(voiceRecorderCallback);
    }


}
